<template>
  <div class="goodesmodelbox">
    <el-dialog
      :showClose="false"
      title="参加活动"
      :visible.sync="centerDialogVisible"
      height="100%"
      top
      width="100%"
      :fullscreen="true"
    >
      <div class="topSearch">
        <div class="topSearchLeft">
          <el-form
            ref="form"
            :model="this.currentRow"
            label-width="100px"
            style="display: flex"
          >
            <el-form-item label="活动名称:">
              <el-input
                :disabled="true"
                style="width: 150px"
                v-model="this.currentRow.activeName"
              ></el-input>
            </el-form-item>
            <el-form-item label="活动说明:">
              <el-input
                :disabled="true"
                style="width: 150px"
                v-model="this.currentRow.notes"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="activty"
              label="活动时间:"
              prop="startTime"
              v-if="this.enterType === 2 || this.enterType === 4"
              width="110px"
            >
              <el-date-picker
                :disabled="true"
                style="width: 400px"
                v-model="chooseTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="{
                  disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                  },
                }"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="商品名称:"
              v-if="this.enterType != 2 && this.enterType != 4"
            >
              <el-input
                v-model="goodsName"
                :style="{ width: '200px' }"
                placeholder="商品名称"
                clearable
                @clear="clearHandle"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="请选择:"
              v-if="this.enterType != 2 && this.enterType != 4"
            >
              <el-cascader
                :style="{ width: '160px' }"
                :options="options"
                :show-all-levels="false"
                @change="optionsID"
                v-model="catgeory"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-row
              v-if="this.enterType === 2 || this.enterType === 4"
              :class="!showAll ? 'btnRow' : 'unBtnRow'"
            >
              <!-- <el-form-item
                label="PC活动横幅"
                class="PCItem"
                prop="pcBannerSrc"
                v-if="this.enterType === 2"
              >
                <el-image
                  style="width: 100px; height: 100px"
                  :src="this.currentRow.pcBannerSrc"
                  :preview-src-list="[this.currentRow.pcBannerSrc]"
                >
                </el-image>
              </el-form-item> -->
              <!-- <el-form-item
                label="H5活动横幅"
                prop="h5BannerSrc"
                class="HItem"
                v-if="this.enterType === 2"
              >
                <el-image
                  style="width: 100px; height: 100px"
                  :src="this.currentRow.h5BannerSrc"
                  :preview-src-list="[this.currentRow.h5BannerSrc]"
                >
                </el-image>
              </el-form-item> -->
              <el-form-item label="商品名称:" style="margin-left: -10px">
                <el-input
                  v-model="goodsName"
                  :style="{ width: '150px' }"
                  placeholder="商品名称"
                  clearable
                  @clear="clearHandle"
                ></el-input>
              </el-form-item>
              <el-form-item label="请选择:">
                <el-cascader
                  :style="{ width: '160px' }"
                  :options="options"
                  :show-all-levels="false"
                  @change="optionsID"
                  v-model="catgeory"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <div class="topSearchRight">
          <el-button
            type="primary"
            :style="{ marginLeft: '20px' }"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button :style="{ marginLeft: '20px' }" @click="chongzhi">
            重置
          </el-button>
          <el-row class="expand">
            <el-col
              :span="1.5"
              class="elrowBtn"
              v-if="this.enterType === 2 || this.enterType === 4"
            >
              <el-button type="text" size="max" @click="closeSearch">
                {{ word }}
                <i
                  :class="showAll ? 'el-icon-arrow-down ' : 'el-icon-arrow-up'"
                ></i>
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>

      <div></div>
      <div class="tableBox">
        <div class="topButton">
          <div class="topButtonLeft">
            <el-button type="primary" @click="submitHandle">提交</el-button>

            <el-button @click="cancelgoodesmodel">取 消</el-button>
          </div>
          <div class="topButtonRight">
            <el-button
              circle
              icon="el-icon-refresh-right"
              @click="RefreshHandle"
            >
            </el-button>
          </div>
        </div>
        <div class="divBox">
          <el-table
            v-loading="loading"
            :cell-style="{ 'text-align': 'center' }"
            :data="goodsList"
            :header-cell-style="{ 'text-align': 'center' }"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              :selectable="canBeSelect"
              width="55"
            ></el-table-column>
            <el-table-column fixed label="排序" prop="sort" width="70">
              <template slot-scope="scope">
                <div class="flex-container">
                  <span class="flex-item">
                    <!-- 序号 -->
                    {{ scope.$index + 1 }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品图片" prop="thumb">
              <template slot-scope="scope">
                <div class="cell_1">
                  <img
                    :src="scope.row.thumb"
                    alt=""
                    style="width: 40px; height: 40px"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goodsName">
            </el-table-column>
            <el-table-column label="总库存" prop="stock"> </el-table-column>
            <el-table-column label="会员价格" prop="orderAmount">
              <template slot-scope="scope">
                {{ scope.row.priceCurrent / 100 }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="paging">
          <el-pagination
            background
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 40]"
            layout="sizes,total, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
        <div class="SpecificationsBox" v-if="this.enterType === 4">
          <el-table :data="SpecificationsData" stripe>
            <el-table-column prop="goodsName" label="商品名称" align="center">
            </el-table-column>
            <el-table-column prop="levelPath" label="规格属性" align="center">
            </el-table-column>
            <el-table-column prop="stock" label="库存数量" align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.stock"
                  size="mini"
                  @change="updateStock(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.price"
                  size="mini"
                  @change="updatePrice(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  @click="delsctSpecifications(scope.row)"
                  type="text"
                  size="small"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  StatisticInfo,
  ParticipateInList,
  SubmitActiveGoods,
  SubmitActiveGoodsTwo,
  GoodsSpecifications,
} from "@/api/mallApi/managementend/marketing";
import { getCategoryList } from "@/api/mallApi/goodsOnsell/goodsOnsell";

export default {
  name: "ParticipateIn",
  components: {},
  props: {
    centerDialogVisible: Boolean,
    currentRow: Object,
    enterType: Number,
    cancelSubmit: Number,
  },
  data() {
    return {
      showAll: false,
      fileList2: [],
      fileList: [],
      catgeory: [],
      options: [],
      goodsName: "",
      loading: false,
      goodsList: [],
      currentPage: 1, // 分页
      total: 0,
      pageSize: 10,
      centerDialogVisible2: false,
      enterType2: 0,
      mallName: "",
      selectedRows: [], // 表格 多选内容
      categoryId: null,
      chooseTime: null,
      SpecificationsInfo: null,
      SpecificationsData: [],
    };
  },
  computed: {
    word: function () {
      if (this.showAll == false) {
        //对文字进行处理
        return "收起";
      } else {
        return "展开";
      }
    },
  },
  methods: {
    updatePrice(e) {},
    updateStock(e) {},
    delsctSpecifications(row) {
      this.$confirm("是否确认删除改规格?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 使用 filter 方法移除匹配的项
          this.SpecificationsData = this.SpecificationsData.filter(
            (item) =>
              item.activeId !== row.activeId ||
              item.goodsName !== row.goodsName ||
              item.levelPath !== row.levelPath ||
              item.mallCode !== row.mallCode ||
              item.mallName !== row.mallName ||
              item.needId !== row.needId ||
              item.price !== row.price ||
              item.specItemAttrId !== row.specItemAttrId ||
              item.stock !== row.stock
          );
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    chongzhi() {
      this.catgeory = [];
      this.goodsName = "";
      this.RefreshHandle();
    },
    submitHandle() {
      if (this.selectedRows.length === 0) {
        this.$message({
          message: "请勾选需要参加活动的商品再提交！",
          type: "warning",
        });
        return;
      }
      this.loading = true;
      if (this.enterType === 4) {
        this.SpecificationsData = this.SpecificationsData.map((item) => {
          item.price *= 100;
          return item;
        });
        SubmitActiveGoodsTwo(this.SpecificationsData)
          .then((res) => {
            if (res.code !== "00000") return;
            this.$message({
              message: "商品已成功提交参与活动！",
              type: "success",
            });
            this.RefreshHandle();
            this.SpecificationsData = [];
            this.loading = false;
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      } else {
        SubmitActiveGoods(this.selectedRows)
          .then((res) => {
            if (res.code !== "00000") return;
            this.$message({
              message: "商品已成功提交参与活动！",
              type: "success",
            });
            this.RefreshHandle();
            this.loading = false;
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      }
    },
    canBeSelect(row) {
      if (row.attend) {
        return false; // 返回false 可以选择
      } else {
        return true; // 返回true 禁止选择
      }
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      // console.log("选中复选框", this.selectedRows);
      if (this.enterType === 4) {
        this.SpecificationsInfo = this.selectedRows
          .map((item) => item.needId)
          .join(",");
        // if (this.selectedRows.length === 0) return;
        this.loading = true;
        const params = {
          goodsIds: this.SpecificationsInfo,
        };
        GoodsSpecifications(params)
          .then((res) => {
            if (res.code !== "00000") return;
            this.SpecificationsData = res.data.map((item) => {
              item.price /= 100;
              return item;
            });
            this.SpecificationsData.forEach((item) => {
              item.activeId = selection[0].activeId;
            });
            this.loading = false;
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      }
      // TODO 在这里进行相应的操作，如发起请求等
    }, // 表格多选
    optionsID(e) {
      this.categoryId = e[1] || null;
    }, //选中商品分类
    getGoodsTypeList() {
      getCategoryList("isEnabled = 1").then((res) => {
        if (res.code === "00000") {
          this.options = res.data.map((item) => {
            if (item.categoryDTOList && item.categoryDTOList.length > 0) {
              return {
                value: item.id,
                label: item.categoryDTOList[0].categoryName,
                children: item.categoryDTOList.map((subItem) => {
                  return {
                    value: subItem.id,
                    label: subItem.categoryName,
                    // 如果需要，可以添加更多属性
                  };
                }),
              };
            } else {
              // 处理 categoryDTOList 为空的情况，可以根据需求进行适当的处理
              return {
                value: item.id,
                label: item.categoryName,
              };
            }
          });
        }
      });
    }, //商品属性
    cancelgoodesmodel2() {
      this.enterType2 = 0;
      this.centerDialogVisible2 = false;
    },
    clearHandle() {
      this.getGoodsListHandle();
    },
    RefreshHandle() {
      this.getGoodsListHandle();
      this.getGoodsTypeList();
    },
    handleSearch() {
      this.currentPage = 1;
      this.getGoodsListHandle();
    },
    saveActiveHandle() {},
    cancelgoodesmodel() {
      this.$emit("cancelgoodesmodel", false);
      this.SpecificationsData = [];
    }, // 取消按钮 传值
    getGoodsListHandle() {
      this.loading = true;
      const params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        activeId: this.currentRow.id,
        goodsName: this.goodsName,
        needId: this.categoryId,
      };
      ParticipateInList(params)
        .then((res) => {
          if (res.code !== "00000") return;
          this.goodsList = res.data.rows;
          this.total = parseInt(res.data.totalRows);
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getGoodsListHandle();
    },
    handleCurrentChange(val) {
      // 分页
      this.currentPage = val;
      this.getGoodsListHandle();
    },
    //展开收起
    closeSearch() {
      this.showAll = !this.showAll;
    },
  },
  mounted() {},
  created() {
    // console.log(this.enterType);
    this.getGoodsListHandle();
    this.getGoodsTypeList();
    if (this.enterType === 2 || this.enterType === 4) {
      this.chooseTime = [this.currentRow.startTime, this.currentRow.endTime];
    }
  },
  watch: {
    centerDialogVisible(newVal) {
      // 监听 centerDialogVisible 的变化
      if (!newVal) {
        // 当 centerDialogVisible 变为 false 时触发事件
        this.$emit("close-dialog");
      }
    },
    selectedRows: {
      handler(newValue) {
        // 数组发生变化时，isButtonDisabled计算属性会重新计算，从而更新按钮的禁用状态
        this.isButtonDisabled = newValue.length === 0;
      },
      deep: true,
      immediate: true, // 立即执行处理函数
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
  font-weight: 100;
  color: #000000;
}
::v-deep .activty {
  width: 115px !important;
  margin-left: 10px;
}
.goodesmodelbox {
  .topSearch {
    width: 98%;
    margin: 1%;
    height: auto;
    background: #fff;
    display: flex;
    justify-content: space-between;
    position: relative;
    .unBtnRow {
      display: none;
    }

    .topSearchLeft {
      display: flex;
      align-items: flex-start;
    }
    .topSearchRight {
      width: 18%;
      height: auto;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 30px;
      ::v-deep .expand {
        margin-bottom: 5px;
        margin-left: 10px;
      }
    }
    .btnRow {
      display: flex;
      align-items: flex-start;
      margin-left: -615px;
      margin-top: 50px;
    }
  }
  .topButton {
    width: 100%;
    min-height: 65px;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    .topButtonLeft {
      margin-top: 10px;
      margin-left: 15px;
    }
    .topButtonRight {
      margin-top: 10px;
      margin-right: 30px;
    }
  }
  .tableBox {
    width: 100%;
    min-height: 750px;
    margin-top: 1%;
    margin-bottom: 1%;
    margin-left: 1%;
    background: #fff;
    .divBox {
      width: 98%;
      margin-left: 1%;
      margin-bottom: 15px;
      border: 1px solid #dcdee2;
    }
    .SpecificationsBox {
      width: 98%;
      margin-left: 1%;
      margin-bottom: 15px;
      border: 1px solid #dcdee2;
      ::v-deep .el-table th,
      .el-table td {
        text-align: center;
      }
    }
    .paging {
      width: 99%;
      height: 50px;
      margin-bottom: 15px;
      // background-color: antiquewhite;
      display: flex;
      align-items: end;
      justify-content: end;
    }
  }
}
</style>
